package day10;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author oldliu
 * @since 1.0
 */
public class ChatServer {
    public static void main(String[] args) {
        ServerSocket st = null;
        try {
            st = new ServerSocket(9999);
            System.out.println("服务器启动成功，监听在9999端口");
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        while (true) {
            Socket s = null;
            try {
                s = st.accept();
                System.out.println(s + "连接成功！");
                InputStream in = s.getInputStream();
                OutputStream out = s.getOutputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                PrintWriter pw = new PrintWriter(out, true);//true表示自动刷新
                //聊天的方式：客户端，服务器回答
                while (true) {
                    String ask = br.readLine();//以 \n作为结束标记
                    String reply = "你说的事情:" + ask + ",朕知道了";
                    pw.println(reply);
                    if ("byebye".equals(ask))
                        break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (s != null) {
                    try {
                        System.out.println(s + "退出了");
                        s.close();
                    } catch (IOException e) {

                    }
                }
            }

        }
    }
}
